<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>待办事项管理</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        .todo-container {
            max-width: 600px;
            margin: 50px auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            padding: 30px;
        }
        .todo-item {
            display: flex;
            align-items: center;
            padding: 15px;
            margin-bottom: 10px;
            background: #f8f9fa;
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        .todo-item:hover {
            background: #e9ecef;
        }
        .todo-item.completed {
            opacity: 0.7;
        }
        .todo-item.completed .todo-text {
            text-decoration: line-through;
            color: #6c757d;
        }
        .todo-text {
            flex: 1;
            margin: 0 15px;
            font-size: 16px;
        }
        .btn-group {
            display: flex;
            gap: 5px;
        }
        .stats {
            text-align: center;
            margin: 20px 0;
            color: #6c757d;
        }
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }
        .loading {
            text-align: center;
            padding: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="todo-container">
            <h1 class="text-center mb-4">
                <i class="fas fa-tasks text-primary"></i> 待办事项管理
            </h1>
            
            <form id="todoForm" class="mb-4">
                <div class="input-group">
                    <input type="text" id="todoInput" class="form-control" placeholder="添加新的待办事项..." required>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-plus"></i> 添加
                    </button>
                </div>
            </form>
            
            <div class="stats">
                <span id="statsText">加载中...</span>
            </div>
            
            <div id="todoList">
                <div class="loading">
                    <i class="fas fa-spinner fa-spin"></i> 加载中...
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
    <script>
        const API_BASE = '/api/todos';
        
        let todos = [];
        
        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadTodos();
            document.getElementById('todoForm').addEventListener('submit', handleAddTodo);
        });
        
        // 加载待办事项
        async function loadTodos() {
            try {
                const response = await fetch(API_BASE);
                todos = await response.json();
                renderTodos();
            } catch (error) {
                console.error('加载失败:', error);
                document.getElementById('todoList').innerHTML = 
                    '<div class="empty-state text-danger">加载失败，请刷新页面重试</div>';
            }
        }
        
        // 渲染待办事项列表
        function renderTodos() {
            const todoList = document.getElementById('todoList');
            const statsText = document.getElementById('statsText');
            
            if (todos.length === 0) {
                todoList.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-clipboard-list fa-3x mb-3"></i>
                        <p>暂无待办事项</p>
                    </div>
                `;
                statsText.textContent = '暂无待办事项';
                return;
            }
            
            const completedCount = todos.filter(t => t.completed).length;
            statsText.textContent = `总共 ${todos.length} 项，已完成 ${completedCount} 项`;
            
            todoList.innerHTML = todos.map(todo => `
                <div class="todo-item ${todo.completed ? 'completed' : ''}" data-id="${todo.id}">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" 
                               ${todo.completed ? 'checked' : ''} 
                               onchange="toggleTodo(${todo.id}, ${!todo.completed})">
                    </div>
                    <div class="todo-text">${escapeHtml(todo.title)}</div>
                    <div class="btn-group">
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteTodo(${todo.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            `).join('');
        }
        
        // 添加待办事项
        async function handleAddTodo(e) {
            e.preventDefault();
            const input = document.getElementById('todoInput');
            const title = input.value.trim();
            
            if (!title) return;
            
            try {
                const response = await fetch(API_BASE, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        title: title,
                        completed: false
                    })
                });
                
                if (response.ok) {
                    const newTodo = await response.json();
                    todos.push(newTodo);
                    renderTodos();
                    input.value = '';
                }
            } catch (error) {
                alert('添加失败，请重试');
            }
        }
        
        // 切换完成状态
        async function toggleTodo(id, completed) {
            const todo = todos.find(t => t.id === id);
            if (!todo) return;
            
            todo.completed = completed;
            
            try {
                const response = await fetch(`${API_BASE}/${id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(todo)
                });
                
                if (response.ok) {
                    renderTodos();
                } else {
                    todo.completed = !completed;
                }
            } catch (error) {
                todo.completed = !completed;
                alert('更新失败，请重试');
            }
        }
        
        // 删除待办事项
        async function deleteTodo(id) {
            if (!confirm('确定要删除这个待办事项吗？')) return;
            
            try {
                const response = await fetch(`${API_BASE}/${id}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    todos = todos.filter(t => t.id !== id);
                    renderTodos();
                }
            } catch (error) {
                alert('删除失败，请重试');
            }
        }
        
        // HTML转义
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
</body>
</html>
